<template>
  <div class="bg-fa of">
    <section id="index" class="container">
      <header class="comm-title">
        <h2 class="fl tac">
          <span class="c-333">订单列表</span>
        </h2>
        <div class="search-container">
          <el-input v-model="searchTitle" placeholder="请输入订单标题搜索" clearable @clear="handleSearch"
            @keyup.enter="handleSearch" style="width: 300px; margin-bottom: 20px">
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>
      </header>
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="orderNo" label="订单编号" width="240"></el-table-column>
        <el-table-column prop="title" label="订单标题"></el-table-column>
        <el-table-column prop="totalFee" label="订单金额">
          <template #default="scope">
            {{ scope.row.totalFee }} 元
          </template>
        </el-table-column>
        <el-table-column label="订单状态">
          <template #default="scope">
            <el-tag v-if="scope.row.orderStatus === '未支付'">
              {{ scope.row.orderStatus }}
            </el-tag>
            <el-tag v-else-if="scope.row.orderStatus === '支付成功'" type="success">
              {{ scope.row.orderStatus }}
            </el-tag>
            <el-tag v-else-if="scope.row.orderStatus === '超时已关闭'" type="warning">
              {{ scope.row.orderStatus }}
            </el-tag>
            <el-tag v-else-if="scope.row.orderStatus === '用户已取消'" type="info">
              {{ scope.row.orderStatus }}
            </el-tag>
            <el-tag v-else-if="scope.row.orderStatus === '退款中'" type="danger">
              {{ scope.row.orderStatus }}
            </el-tag>
            <el-tag v-else-if="scope.row.orderStatus === '已退款'" type="info">
              {{ scope.row.orderStatus }}
            </el-tag>
            <el-tag v-else-if="scope.row.orderStatus === '退款异常'" type="danger">
              {{ scope.row.orderStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentType" label="支付方式" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.paymentType === '微信'" type="success">
              {{ scope.row.paymentType }}
            </el-tag>
            <el-tag v-else-if="scope.row.paymentType === '支付宝'" type="primary">
              {{ scope.row.paymentType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.orderStatus === '未支付'" type="text"
              @click="cancel(scope.row.orderNo, scope.row.paymentType)">取消</el-button>
            <el-button v-if="scope.row.orderStatus === '支付成功'" type="text"
              @click="refund(scope.row.orderNo, scope.row.paymentType)">退款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
          :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </section>

    <!-- 退款对话框 -->
    <el-dialog v-model="refundDialogVisible" @close="closeDialog" width="350px" center>
      <el-form>
        <el-form-item label="退款原因">
          <el-select v-model="reason" placeholder="请选择退款原因">
            <el-option label="不喜欢" value="不喜欢"></el-option>
            <el-option label="买错了" value="买错了"></el-option>
            <el-option label="商家态度不好" value="商家态度不好"></el-option>
            <el-option label="天天快乐" value="2025愿望成真，找到好工作"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="toRefunds()" :disabled="refundSubmitBtnDisabled">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { getOrderInfoList } from '@/api/orderInfo'
import {
  refundsPayService,
  cancelService
} from '@/api/wxPay'
import { aliPayCancleService,aliPayRefundsService } from '@/api/aliPay'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const tableData = ref([])
const refundDialogVisible = ref(false)
const orderNo = ref('')
const reason = ref('')
const refundSubmitBtnDisabled = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchTitle = ref('')

//退款类型
const refundType = ref('')

onMounted(() => {
  fetchData()
})

const fetchData = async () => {
  try {
    loading.value = true
    const response = await getOrderInfoList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchTitle.value
    })
    tableData.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

const cancel = async (orderNo, paymentType) => {
  loading.value = true
  try {
    if (paymentType === '微信') {
      await cancelService(orderNo)
    } else if (paymentType === '支付宝') {
      await aliPayCancleService(orderNo)
    }
    ElMessage.success('取消订单成功')
    fetchData()
  } catch (error) {
    console.error('取消订单失败:', error)
    ElMessage.error('取消订单失败')
  } finally {
    loading.value = false
  }
}

const refund = (no,paymentType) => {
  refundDialogVisible.value = true
  orderNo.value = no
  refundType.value = paymentType
}

const closeDialog = () => {
  refundDialogVisible.value = false
  orderNo.value = ''
  reason.value = ''
  refundSubmitBtnDisabled.value = false
}

const toRefunds = async () => {
  loading.value = true
  refundSubmitBtnDisabled.value = true
  try {
    if (refundType.value === '微信') {
      await refundsPayService(orderNo.value, reason.value)
    }else if (refundType.value === '支付宝') {
      await aliPayRefundsService(orderNo.value, reason.value)
    }
    closeDialog()
    fetchData()
    ElMessage.success('退款成功')
  } catch (error) {
    console.error('退款失败:', error)
    refundSubmitBtnDisabled.value = false
  }finally {
    loading.value = false
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.comm-title {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.search-container {
  margin-top: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  margin-right: 5px;
}
</style>